/**
* @Author:wjp
* @Date:2021/1/25 1:30 下午
 */
package xhttp

import (
	"encoding/json"
	"git.xycm.com/pkg/xerr"
	"github.com/tal-tech/go-zero/core/logx"
	"net/http"
)

type (
	NullJson struct{}

	ResponseSuccessBean struct {
		Code int         `json:"code"`
		Msg  string      `json:"msg"`
		Data interface{} `json:"data"`
	}
)

func HttpSuccess(w http.ResponseWriter, data interface{}) {

	WriteJson(w, 200, ResponseSuccessBean{
		Code: 0,
		Msg:  "success",
		Data: data,
	})

}

type ResponseErrorBean struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

func HttpError(w http.ResponseWriter, errCode int) {
	WriteJson(w, 200, ResponseSuccessBean{
		Code: errCode,
		Msg:  xerr.NMapErrMsg(errCode),
		Data: "",
	})
}
func HttpRespError(w http.ResponseWriter, err error) {
	e := xerr.ErrorFmt(err)
	WriteJson(w, 200, ResponseSuccessBean{
		Code:e.ErrCode,
		Msg:  e.ErrMsg,
		Data: "",
	})
}

func WriteJson(w http.ResponseWriter, code int, v interface{}) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)

	if bs, err := json.Marshal(v); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	} else if n, err := w.Write(bs); err != nil {
		// http.ErrHandlerTimeout has been handled by http.TimeoutHandler,
		// so it's ignored here.
		if err != http.ErrHandlerTimeout {
			logx.Errorf("write response failed, error: %s", err)
		}
	} else if n < len(bs) {
		logx.Errorf("actual bytes: %d, written bytes: %d", len(bs), n)
	}
}
